package com.erHuo.controller;

import com.erHuo.common.utils.Stringutils;
import com.erHuo.entity.AcctUser;
import com.erHuo.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 用户控制器
 * Created by djx on 2017/4/24.
 */
@Controller
@RequestMapping("/")
public class IndexController {

    private static final Logger LOGGER = Logger.getLogger(IndexController.class);

    private static final String key = "erhuo_app";

    @Autowired
    private UserService userService;

    /**
     * 主页
     * @param httpSession
     * @param request
     * @return
     */
    @RequestMapping("/")
    public String index(HttpSession httpSession, HttpServletRequest request){
        AcctUser acctUser = (AcctUser) httpSession.getAttribute("acctuser");
        request.setAttribute("acctuser",acctUser);
        return "index";
    }

    /**
     * 注册页面
     * @return
     */
    @RequestMapping("/register")
    public String register(){
        return "register";
    }

    /**
     * 登录页面
     * @return
     */
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping("/logout")
    public void logout(HttpSession httpSession, HttpServletResponse response){
        httpSession.invalidate();
        try {
            response.sendRedirect("/");
        }catch (IOException e){
            System.out.println(e);
        }
    }

    /**
     * 获取验证码
     * @param cellphone 手机号
     * @param timeStamp 时间戳
     * @param deviceId 设备ID
     * @param summary   加密字段
     * @return json
     */
    @RequestMapping(value = "/getVerifyCode",produces = "text/json;charset=UTF-8")
    public @ResponseBody
    String getVerifyCode(@RequestParam(value="cellphone", required = false) String cellphone,
                         @RequestParam(value="timestamp", required = false) String timeStamp,
                         @RequestParam(value="deviceId", required = false) String deviceId,
                         @RequestParam(value="summary", required = false) String summary){
        Map<String, Object> resultMap = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        //拼接测试加密字段
        String testSummary = key+cellphone+timeStamp;
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            testSummary = encoder.encode(testSummary.getBytes("UTF-8"));
        }catch (UnsupportedEncodingException e){
            LOGGER.error("错误-----获取验证码："+e);
        }

        if(!testSummary.equals(summary)){
            resultMap.put("code",401);
            resultMap.put("msg","加密字段验证失败");
        }else{
            String verifyCode = Stringutils.getRandomString(6);
            // TODO: 2017/5/3 发送手机验证码代码


            AcctUser acctuser = new AcctUser();
            List<AcctUser> userList = userService.findAcctUserByCellPhone(cellphone);
            if (userList.size()>0){
                acctuser = userList.get(0);
            }else {
                acctuser.setId(UUID.randomUUID()+"");
            }
            // TODO: 2017/5/3 验证码发送是否成功
            if(true){
                acctuser.setVerifyCode(verifyCode);
                acctuser.setCellphone(cellphone);
                acctuser.setDeviceId(deviceId);
                boolean bon = userService.saveOrUpdateAcctUser(acctuser);
                if(bon){
                    resultMap.put("code",200);
                    resultMap.put("msg","成功");
                    resultMap.put("data",verifyCode);
                }else{
                    resultMap.put("code",402);
                    resultMap.put("msg","验证码发送失败");
                }
            }else{
                resultMap.put("code",402);
                resultMap.put("msg","验证码发送失败");
            }
        }

        String json = "";
        try {
            json = mapper.writeValueAsString(resultMap);
        }catch (Exception e){
            LOGGER.error("错误-----获取验证码："+e);
        }

        return json;
    }

    /**
     * APP快速注册
     * @param cellphone 手机
     * @param password  密码
     * @param verifyCode 验证码
     * @param summary  加密验证
     * @param timeStamp  时间戳
     * @return json
     */
    @RequestMapping(value = "/appRegist",produces = "text/json;charset=UTF-8")
    public @ResponseBody
    String appRegist(@RequestParam(value="cellphone", required = false) String cellphone,
                     @RequestParam(value="password", required = false) String password,
                     @RequestParam(value="timestamp", required = false) String timeStamp,
                     @RequestParam(value="verifycode", required = false) String verifyCode,
                     @RequestParam(value="summary", required = false) String summary){

        Map<String, Object> resultMap = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        String testSummary = key + cellphone + timeStamp;
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            testSummary = encoder.encode(testSummary.getBytes("UTF-8"));
        }catch (UnsupportedEncodingException e){
            LOGGER.error("错误-----简易注册："+e);
        }

        if(!testSummary.equals(summary)){
            resultMap.put("code",401);
            resultMap.put("msg","加密字段验证失败");
        }else{
            try {
                password = Stringutils.md5Password(new String(new BASE64Decoder().decodeBuffer(Stringutils.reverse(password)), "UTF-8"));
            }catch (Exception e){
                LOGGER.error("错误-----简易注册："+e);
            }

            List<AcctUser> userList = userService.findAcctUserByCellPhone(cellphone);

            if(userList.size()>0){
                AcctUser acctUser = userList.get(0);
                String testverifyCode = acctUser.getVerifyCode();
                if(!testverifyCode.equals(verifyCode)){
                    resultMap.put("code",403);
                    resultMap.put("msg","手机验证码错误");
                }else{
                    acctUser.setPassword(password);
                    acctUser.setRegisterTime(new Date());
                    boolean bon = userService.saveOrUpdateAcctUser(acctUser);
                    if(bon){
                        resultMap.put("code",200);
                        resultMap.put("msg","成功");
                    }
                }
            }else{
                resultMap.put("code",403);
                resultMap.put("msg","手机验证码错误");
            }
        }
        String json = "";
        try {
            json = mapper.writeValueAsString(resultMap);
        }catch (Exception e){
            LOGGER.error("错误-----简易注册："+e);
        }

        return json;
    }


    /**
     * APP注册(非手机号)
     * @param username 用户名
     * @param password  密码
     * @param summary  加密验证
     * @param timeStamp  时间戳
     * @return json
     */
    @RequestMapping(value = "/appUserRegist",produces = "text/json;charset=UTF-8")
    public @ResponseBody
    String appUserRegist(@RequestParam(value="username", required = false) String username,
                         @RequestParam(value="password", required = false) String password,
                         @RequestParam(value="timestamp", required = false) String timeStamp,
                         @RequestParam(value="summary", required = false) String summary){

        Map<String, Object> resultMap = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        String testSummary = key + username + timeStamp;
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            testSummary = encoder.encode(testSummary.getBytes("UTF-8"));
        }catch (UnsupportedEncodingException e){
            LOGGER.error("错误-----注册："+e);
        }

        if(!testSummary.equals(summary)){
            resultMap.put("code",401);
            resultMap.put("msg","加密字段验证失败");
        }else{
            try {
                password = Stringutils.md5Password( new String(new BASE64Decoder().decodeBuffer(Stringutils.reverse(password)), "UTF-8"));
            }catch (Exception e){
                LOGGER.error("错误-----注册："+e);
            }

            List<AcctUser> userList = userService.findAcctUserByEmail(username);
            List<AcctUser> userList1 = userService.findAcctUserByCellPhone(username);

            if(userList.size()>0 || userList1.size()>0){
                resultMap.put("code",404);
                resultMap.put("msg","该用户已存在");
            }else{
                AcctUser acctuser = new AcctUser();
                if(username.contains("@")){
                    acctuser.setEmail(username);
                }else{
                    acctuser.setCellphone(username);
                }
                acctuser.setPassword(password);
                acctuser.setRegisterTime(new Date());
                boolean bon = userService.saveOrUpdateAcctUser(acctuser);
                if(bon){
                    resultMap.put("code",200);
                    resultMap.put("msg","成功");
                }else{
                    resultMap.put("code",405);
                    resultMap.put("msg","注册失败");
                }
            }
        }
        String json = "";
        try {
            json = mapper.writeValueAsString(resultMap);
        }catch (Exception e){
            LOGGER.error("错误-----注册："+e);
        }

        return json;
    }


    /**
     * 登录
     * @param username 用户登录名，邮箱或者手机号
     * @param password 密码
     * @param timeStamp 时间戳
     * @param summary 加密字段
     * @return json
     */
    @RequestMapping(value = "/appLogin",produces = "text/json;charset=UTF-8")
    public @ResponseBody
    String appLogin( @RequestParam(value="username", required = false) String username,
                     @RequestParam(value="password", required = false) String password,
                     @RequestParam(value="timestamp", required = false) String timeStamp,
                     @RequestParam(value="summary", required = false) String summary){

        Map<String, Object> resultMap = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        String testSummary = key + username + timeStamp;
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            testSummary = encoder.encode(testSummary.getBytes("UTF-8"));
        }catch (UnsupportedEncodingException e){
            LOGGER.error("错误-----登录："+e);
        }

        if(!testSummary.equals(summary)){
            resultMap.put("code",401);
            resultMap.put("msg","加密字段验证失败");
        }else{
            try {
                password = Stringutils.md5Password( new String(new BASE64Decoder().decodeBuffer(Stringutils.reverse(password)), "UTF-8"));
            }catch (Exception e){
                LOGGER.error("错误-----登录："+e);
            }

            List<AcctUser> list = new ArrayList<AcctUser>();
            if(username.contains("@")){
                list = userService.findAcctUserByEmail(username);
            }else{
                list = userService.findAcctUserByCellPhone(username);
            }
            if(list.size()<1){
                resultMap.put("code",406);
                resultMap.put("msg","该用户不存在");
            }else{
                AcctUser acctUser = list.get(0);
                if(password.equals(acctUser.getPassword())){
                    Map<String ,Object> userMap = new HashMap<>();
                    userMap.put("cellphone",acctUser.getCellphone());
                    userMap.put("email",acctUser.getEmail());
                    userMap.put("sex",acctUser.getSex());
                    userMap.put("age",acctUser.getAge());
                    userMap.put("nickName",acctUser.getNickName());
                    userMap.put("skillIds",acctUser.getSkillIds());
                    resultMap.put("data",userMap);
                    resultMap.put("code",200);
                    resultMap.put("msg","成功");
                }else{
                    resultMap.put("code",407);
                    resultMap.put("msg","账号或密码错误");
                }
            }

        }
        String json = "";
        try {
            json = mapper.writeValueAsString(resultMap);
        }catch (Exception e){
            LOGGER.error("错误-----登录："+e);
        }

        return json;
    }


    /**
     * 登录
     * @param username 用户登录名，邮箱或者手机号
     * @param password 密码
     * @return json
     */
    @RequestMapping(value = "/tologin",produces = "text/json;charset=UTF-8")
    public @ResponseBody
    String tologin(@RequestParam(value="username", required = false) String username,
                   @RequestParam(value="password", required = false) String password,
                   HttpSession httpSession){

        Map<String, Object> resultMap = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        try {
            password = Stringutils.md5Password(password);
        }catch (Exception e){
            LOGGER.error("错误-----登录："+e);
        }

        List<AcctUser> list = new ArrayList<AcctUser>();
        if(username.contains("@")){
            list = userService.findAcctUserByEmail(username);
        }else{
            list = userService.findAcctUserByCellPhone(username);
        }
        if(list.size()>0){
            AcctUser acctUser = list.get(0);
            if(password.equals(acctUser.getPassword())){
                resultMap.put("code",200);
                resultMap.put("msg","成功");
                httpSession.setAttribute("acctuser",acctUser);
            }else{
                resultMap.put("code",407);
                resultMap.put("msg","账号或密码错误");
            }
        }else{
            resultMap.put("code",406);
            resultMap.put("msg","该用户不存在");
        }
        String json = "";
        try {
            json = mapper.writeValueAsString(resultMap);
        }catch (Exception e){
            LOGGER.error("错误-----登录："+e);
        }

        return json;
    }

    /**
     * 登录
     * @param username 用户登录名，邮箱或者手机号
     * @param password 密码
     * @return json
     */
    @RequestMapping(value = "/toregister",produces = "text/json;charset=UTF-8")
    public @ResponseBody
    String toregister(@RequestParam(value="username", required = false) String username,
                      @RequestParam(value="password", required = false) String password,
                      @RequestParam(value="nickname", required = false) String nickname,
                      HttpSession httpSession){

        Map<String, Object> resultMap = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        try {
            password = Stringutils.md5Password(password);
        }catch (Exception e){
            LOGGER.error("错误-----登录："+e);
        }

        List<AcctUser> userList = userService.findAcctUserByEmail(username);
        List<AcctUser> userList1 = userService.findAcctUserByCellPhone(username);

        if(userList.size()>0 || userList1.size()>0){
            resultMap.put("code",404);
            resultMap.put("msg","该用户已存在");
        }else{
            AcctUser acctuser = new AcctUser();
            if(username.contains("@")){
                acctuser.setEmail(username);
            }else{
                acctuser.setCellphone(username);
            }
            acctuser.setNickName(nickname);
            acctuser.setId(UUID.randomUUID()+"");
            acctuser.setPassword(password);
            acctuser.setRegisterTime(new Date());
            boolean bon = userService.saveOrUpdateAcctUser(acctuser);
            if(bon){
                resultMap.put("code",200);
                resultMap.put("msg","成功");
                httpSession.setAttribute("acctuser",acctuser);
            }else{
                resultMap.put("code",405);
                resultMap.put("msg","注册失败");
            }
        }
        String json = "";
        try {
            json = mapper.writeValueAsString(resultMap);
        }catch (Exception e){
            LOGGER.error("错误-----登录："+e);
        }

        return json;
    }

    /**
     * 用户名查询
     * @param username 用户登录名，邮箱或者手机号
     * @return json
     */
    @RequestMapping(value = "/checkUser",produces = "text/json;charset=UTF-8")
    public @ResponseBody
    String checkUser(@RequestParam(value="username", required = false) String username
    ){

        Map<String, Object> resultMap = new HashMap<>();

        List<AcctUser> list = getAcctUser(username);

        if(list.size()>0) {
            resultMap.put("code",404);
            resultMap.put("msg","该用户已存在");
        }else{
            resultMap.put("code",200);
            resultMap.put("msg","成功");
        }

        ObjectMapper mapper = new ObjectMapper();

        String json = "";
        try {
            json = mapper.writeValueAsString(resultMap);
        }catch (Exception e){
            LOGGER.error("错误-----用户名检测："+e);
        }

        return json;
    }

    /**
     * 根据用户名查询用户
     * @param username 用户名
     * @return list
     */
    public List<AcctUser> getAcctUser(String username){
        List<AcctUser> list;
        if(username.contains("@")){
            list = userService.findAcctUserByEmail(username);
        }else{
            list = userService.findAcctUserByCellPhone(username);
        }
        return list;
    }
}
